<template>
  <div class="notification-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>通知管理</span>
          <el-button type="primary" @click="showCreateDialog">
            发布通知
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="通知类型">
          <el-select v-model="searchForm.type" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="(label, value) in notificationTypeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接收对象">
          <el-select v-model="searchForm.target" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="(label, value) in targetTypeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 通知列表 -->
      <el-table :data="notificationList" style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag :type="getNotificationTagType(scope.row.type)">
              {{ notificationTypeMap[scope.row.type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="接收对象" width="120">
          <template #default="scope">
            {{ targetTypeMap[scope.row.target] }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 通知编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '发布通知' : '编辑通知'"
      width="60%"
    >
      <el-form
        ref="notificationForm"
        :model="notificationForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notificationForm.title" />
        </el-form-item>

        <el-form-item label="通知类型" prop="type">
          <el-select v-model="notificationForm.type">
            <el-option
              v-for="(label, value) in notificationTypeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="接收对象" prop="target">
          <el-select v-model="notificationForm.target">
            <el-option
              v-for="(label, value) in targetTypeMap"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="6"
          />
        </el-form-item>

        <el-form-item label="发送方式">
          <el-checkbox-group v-model="notificationForm.sendMethods">
            <el-checkbox label="system">系统通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="定时发送">
          <el-switch v-model="notificationForm.scheduled" />
        </el-form-item>

        <el-form-item
          v-if="notificationForm.scheduled"
          label="发送时间"
          prop="scheduleTime"
        >
          <el-date-picker
            v-model="notificationForm.scheduleTime"
            type="datetime"
            placeholder="选择发送时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ dialogType === 'create' ? '发布' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getNotificationList,
  createNotification,
  updateNotification,
  deleteNotification,
  publishNotification
} from '@/api/notification'

// 搜索表单
const searchForm = reactive({
  type: '',
  target: '',
  timeRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 通知列表数据
const notificationList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const notificationForm = reactive({
  title: '',
  type: 'announcement',
  target: 'all',
  content: '',
  sendMethods: ['system'],
  scheduled: false,
  scheduleTime: null
})

// 类型映射
const notificationTypeMap = {
  announcement: '公告',
  exam: '考试通知',
  grade: '成绩通知',
  system: '系统通知'
}

const targetTypeMap = {
  all: '全部用户',
  student: '学生',
  teacher: '教师',
  admin: '管理员'
}

const statusMap = {
  draft: '草稿',
  published: '已发布',
  scheduled: '定时发送'
}

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  target: [
    { required: true, message: '请选择接收对象', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' }
  ],
  scheduleTime: [
    {
      required: true,
      message: '请选择发送时间',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (notificationForm.scheduled && !value) {
          callback(new Error('请选择发送时间'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 初始化数据
onMounted(() => {
  loadNotifications()
})

// 加载通知列表
const loadNotifications = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      type: searchForm.type,
      target: searchForm.target,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    
    const { list, total: totalCount } = await getNotificationList(params)
    notificationList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('加载通知列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取通知类型样式
const getNotificationTagType = (type) => {
  const typeMap = {
    announcement: '',
    exam: 'warning',
    grade: 'success',
    system: 'info'
  }
  return typeMap[type]
}

// 获取状态样式
const getStatusType = (status) => {
  const typeMap = {
    draft: 'info',
    published: 'success',
    scheduled: 'warning'
  }
  return typeMap[status]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadNotifications()
}

// 重置搜索
const resetSearch = () => {
  searchForm.type = ''
  searchForm.target = ''
  searchForm.timeRange = []
  handleSearch()
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogType.value = 'create'
  Object.assign(notificationForm, {
    title: '',
    type: 'announcement',
    target: 'all',
    content: '',
    sendMethods: ['system'],
    scheduled: false,
    scheduleTime: null
  })
  dialogVisible.value = true
}

// 编辑通知
const handleEdit = (notification) => {
  dialogType.value = 'edit'
  Object.assign(notificationForm, notification)
  dialogVisible.value = true
}

// 删除通知
const handleDelete = async (notification) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该通知吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteNotification(notification.id)
    ElMessage.success('删除成功')
    loadNotifications()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialogType.value === 'create') {
      await createNotification(notificationForm)
      ElMessage.success('创建成功')
    } else {
      await updateNotification(notificationForm.id, notificationForm)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadNotifications()
  } catch (error) {
    console.error('保存通知失败:', error)
  }
}

// 发布通知
const handlePublish = async (notification) => {
  try {
    await publishNotification(notification.id)
    ElMessage.success('发布成功')
    loadNotifications()
  } catch (error) {
    console.error('发布通知失败:', error)
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadNotifications()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNotifications()
}
</script>

<style scoped>
.notification-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 